package com.sqly.doc.menu.grjbxx;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.clj.fastblexy.BluetoothService;
import com.clj.fastblexy.data.ScanResult;
import com.clj.fastblexy.iscian.IscianService;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sqly.doc.R;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.ble.xyj.CodeMeasureActivity;
import com.sqly.doc.pojo.BleMeasureRecord;
import com.sqly.doc.pojo.JuMin;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.user.choose_user;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.SweetAlertDialogUtil;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.view.StringUtils;
import com.vivachek.nova.bleproxy.BleProxy;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

//import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * Created by Administrator on 2017/11/22 0022.
 */

public class measure_xy_add extends MyBaseActivity  implements View.OnClickListener{
    TextView kfxyz, kfxyz2, kfxyz3, title, uname, xm, jmid, jmsfzh;
    BleMeasureRecord obj;
    Context con = measure_xy_add.this;
    JuMin j;
    private String url = "";
    boolean isadd = false;//是否是新添加
    LinearLayout back;

    private Button btn_start, btn_stop;
    private ImageView img_loading;
    private Animation operatingAnim;
    private measure_xy_add.ResultAdapter mResultAdapter;
    private ProgressDialog progressDialog;

    private IscianService mBluetoothService;
    private Button stop;
    private TextView textView;
    private Button btnStart;
    private Button btn_cancel;
    private ScrollView scrollView;
    private TextView tvResult;
    private TextView tvMeasuring;
    private EditText edtStart;
    private EditText edtTime;
    private LinearLayout ll_data;
    private ListView listView_device;
    public static int count = 0;
    ScanResult entityDefault = null;

    @Override
    protected void initUI() {
        setContentView(R.layout.measure_xy_add);
        if (getIntent().getStringExtra("type").equals("edit")) {
            obj = (BleMeasureRecord) getIntent().getExtras().getSerializable("b");
            url = HttpUrl.EditGxyfsjl;
            initEditText();
            xm.setClickable(false);
        } else {
            obj=new BleMeasureRecord();
            url = HttpUrl.AddGxyfsjl;
            initEditText();
        }
        initAboutBleView();

        back = (LinearLayout) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {

        } else if (requestCode == 1) {
            j = (JuMin) data.getExtras().getSerializable("j");
            getObject();
        }else if(requestCode == 19){
            mBluetoothService.cancelScan();
            String deviceVal = (String) data.getExtras().getString("deviceVal");
            String deviceVal2 = (String) data.getExtras().getString("deviceVal2");
            String deviceVal3 = (String) data.getExtras().getString("deviceVal3");
            kfxyz.setText(deviceVal);
            kfxyz2.setText(deviceVal2);
            kfxyz3.setText(deviceVal3);
        }
    }

    private void initAboutBleView(){
        btn_start = (Button) findViewById(R.id.btn_start);
        btn_start.setOnClickListener(this);
        btn_stop = (Button) findViewById(R.id.btn_stop);
        stop = (Button) findViewById(R.id.stop);
        textView = (TextView) findViewById(R.id.textView);
        tvResult = (TextView) findViewById(R.id.tv_result);
        tvMeasuring = (TextView) findViewById(R.id.tv_measuring);
        btnStart = (Button) findViewById(R.id.btn_start);
        scrollView = (ScrollView) findViewById(R.id.scroll_container);
        btn_cancel = (Button)findViewById(R.id.btn_cancel);
        edtStart = (EditText)findViewById(R.id.edt_start);
        edtTime = (EditText)findViewById(R.id.edt_time);
        ll_data = (LinearLayout)findViewById(R.id.ll_data);
        listView_device = (ListView) findViewById(R.id.list_device);
        ll_data.setVisibility(View.GONE);
        stop.setOnClickListener(this);
        btn_stop.setOnClickListener(this);
        img_loading = (ImageView) findViewById(R.id.img_loading);
        operatingAnim = AnimationUtils.loadAnimation(this, R.anim.rotate);
        operatingAnim.setInterpolator(new LinearInterpolator());
        progressDialog = new ProgressDialog(this);
        progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {

            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                // TODO Auto-generated method stub
                // Cancel task.
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction()==KeyEvent.ACTION_DOWN) {
                    handler.sendEmptyMessageDelayed(0,1000);
                }
                return false;
            }
        });
        mResultAdapter = new measure_xy_add.ResultAdapter(this);
        listView_device.setAdapter(mResultAdapter);
        listView_device.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mBluetoothService != null) {
                    mBluetoothService.cancelScan();
                    bg = mBluetoothService.connectDevice(mResultAdapter.getItem(position));
                    mResultAdapter.clear();
                    mResultAdapter.notifyDataSetChanged();
                }
            }
        });

        checkPermissions();
    }

    private void initEditText() {
        xm = (TextView) findViewById(R.id.xm);
        if (obj != null && !StringUtils.isEmpty(obj.getJmname())) {
            xm.setText(obj.getJmname());
        } else {
            xm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivityForResult(new Intent(con, choose_user.class).putExtra("cname", "measure_xy_add.class"), 1);
                }
            });
        }
        jmid = (TextView) findViewById(R.id.jmid);
        jmsfzh = (TextView) findViewById(R.id.jmsfzh);
        //空腹血压值
        kfxyz = (TextView) findViewById(R.id.kfxyz);
        kfxyz2 = (TextView) findViewById(R.id.kfxyz2);
        kfxyz3 = (TextView) findViewById(R.id.kfxyz3);
        View.OnClickListener onClickListener= new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String xyjval = (String) SharedPreferencesUtils.getParam(con, "xyjval", "");
                if(null == xyjval || "".equals(xyjval)) {
                    SweetAlertDialogUtil.WarningDialog(con, "提示", "请先绑定蓝牙血压计设备");
                }else if (obj != null && StringUtils.isEmpty(obj.getJmname())) {
                    SweetAlertDialogUtil.WarningDialog(con, "提示", "请点击用户输入框选择用户");
                } else {
                    if(null != entityDefault) {
                        mBluetoothService.cancelScan();
                        bg = mBluetoothService.connectDevice(entityDefault);
                        mResultAdapter.clear();
                        mResultAdapter.notifyDataSetChanged();
                    }
                }
            }
        };
        kfxyz.setOnClickListener(onClickListener);
        kfxyz2.setOnClickListener(onClickListener);
        kfxyz3.setOnClickListener(onClickListener);
        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        title.setText("居民血压测量");
        uname.setText("保存");
        uname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (obj == null)
                    obj = new BleMeasureRecord();
                obj.setVal1(kfxyz.getText().toString());
                obj.setVal2(kfxyz2.getText().toString());
                obj.setVal3(kfxyz3.getText().toString());

                if (null == xm.getText().toString() || xm.getText().toString().equals("")) {
                    SweetAlertDialogUtil.WarningDialog(con, "提示", "请点击用户输入框选择用户");
                } else if (null == kfxyz.getText().toString() || kfxyz.getText().toString().equals("")) {
                    SweetAlertDialogUtil.WarningDialog(con, "提示", "请点击血压值输入框进行血压测量");
                } else if (NetWorkUtils.isNetworkConnected(con)) {
                    RequestParams ps = new RequestParams();
                    ps.add("entity.category", "2");
                    ps.add("entity.jmid", obj.getJmid());
                    ps.add("entity.jmname", obj.getJmname());
                    ps.add("entity.jmsfzh", obj.getJmsfzh());
                    ps.add("entity.val1", obj.getVal1());
                    ps.add("entity.val2", obj.getVal2());
                    ps.add("entity.val3", obj.getVal3());
                    ps.add("entity.blename", obj.getBlename());
                    ps.add("entity.blemac", obj.getBlemac());
                    ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
                    ps.add("type", "2");
                    if (isadd) {
                        url = HttpUrl.AddBleMRecord;
                    } else {
                        ps.add("entity.id", obj.getRid());
                        url = HttpUrl.SaveBleMRecord;
                    }
                    UserClient.get(url, ps, new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                            String content = new String(response);
                            RetMsg ret = JSON.parseObject(content, RetMsg.class);
                            if (ret.getCode().equals("200")) {
                                MyToastUtil.ShowToast(con, "成功");
                            }else{
                                MyToastUtil.ShowToast(con, ret.getInfo());
                            }
                            finish();
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                            MyToastUtil.ShowToast(con, "失败");
                        }
                    });
                }
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

    }

    public void getObject() {
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("CARDNUM", j.getCARDNUM());
        UserClient.get(HttpUrl.GetXxfhGrjbxx, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                Log.i("ycf2", content);
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    if (StringUtils.isEmpty(ret.getOtherParams())) {//other是空的
                        JSONObject j = JSON.parseObject(ret.getRd());
                        obj = new BleMeasureRecord();
                        obj.setJmid(j.getString("JKDAH"));
                        obj.setJmname(j.getString("XINGMING"));
                        obj.setJmsfzh(j.getString("SFZH"));
                        xm.setText(j.getString("XINGMING"));
                        jmid.setText(j.getString("JKDAH"));
                        jmsfzh.setText(j.getString("SFZH"));
                        isadd = true;
                    } else {
                        obj = JSON.parseObject(ret.getRd(), BleMeasureRecord.class);
                    }
                } else {
                    SweetAlertDialogUtil.WarningDialog(con, "提示", ret.getInfo());
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                isadd = true;
                obj = new BleMeasureRecord();
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBluetoothService != null)
            unbindService();
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    mBluetoothService.closeConnect();
                    if (mBluetoothService != null) {
                        mBluetoothService.cancelScan();
                    }
                    if (mBluetoothService != null) {
                        unbindService();
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private BluetoothGatt bg;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start:
                checkPermissions();
                break;

            case R.id.btn_stop:
                if (mBluetoothService != null) {
                    mBluetoothService.cancelScan();
                }
                break;
            case R.id.stop:
                stopConnent();
        }
    }

    private void stopConnent() {
        mBluetoothService.closeConnect();
    }

    private class ResultAdapter extends BaseAdapter {

        private Context context;
        private List<ScanResult> scanResultList;

        ResultAdapter(Context context) {
            this.context = context;
            scanResultList = new ArrayList<>();
        }

        public List<ScanResult> getData() {
            return scanResultList;
        }

        void addResult(ScanResult result) {
            scanResultList.add(result);
        }

        void clear() {
            scanResultList.clear();
        }

        @Override
        public int getCount() {
            return scanResultList.size();
        }

        @Override
        public ScanResult getItem(int position) {
            if (position > scanResultList.size())
                return null;
            return scanResultList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            measure_xy_add.ResultAdapter.ViewHolder holder;
            if (convertView != null) {
                holder = (measure_xy_add.ResultAdapter.ViewHolder) convertView.getTag();
            } else {
                convertView = View.inflate(context, R.layout.adapter_scan_result, null);
                holder = new measure_xy_add.ResultAdapter.ViewHolder();
                convertView.setTag(holder);
                holder.txt_name = (TextView) convertView.findViewById(R.id.txt_name);
                holder.txt_mac = (TextView) convertView.findViewById(R.id.txt_mac);
                holder.txt_rssi = (TextView) convertView.findViewById(R.id.txt_rssi);
            }

            ScanResult result = scanResultList.get(position);
            BluetoothDevice device = result.getDevice();
            String name = device.getName();
            String mac = device.getAddress();
            int rssi = result.getRssi();
            holder.txt_name.setText(name);
            holder.txt_mac.setText(mac);
            holder.txt_rssi.setText(String.valueOf(rssi));
            return convertView;
        }

        class ViewHolder {
            TextView txt_name;
            TextView txt_mac;
            TextView txt_rssi;
        }
    }

    private void bindService() {
        Intent bindIntent = new Intent(this, IscianService.class);
        this.bindService(bindIntent, mFhrSCon, Context.BIND_AUTO_CREATE);
    }

    private void unbindService() {
        this.unbindService(mFhrSCon);
    }

    private ServiceConnection mFhrSCon = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("onServiceConnected","1");
            mBluetoothService = ((IscianService.BluetoothBinder) service).getService();
            mBluetoothService.setScanCallback(callback);
            mBluetoothService.scanDevice();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("onServiceDisconnected","2");
            mBluetoothService = null;
        }
    };

    private BluetoothService.Callback callback = new BluetoothService.Callback() {
        @Override
        public void onStartScan() {
            Log.i("onStartScan","3");
            mResultAdapter.clear();
            mResultAdapter.notifyDataSetChanged();
            img_loading.startAnimation(operatingAnim);
            btn_start.setEnabled(false);
            btn_stop.setVisibility(View.VISIBLE);
        }

        @Override
        public void onScanning(ScanResult result) {
            Log.i("onScanning","4");
            mResultAdapter.addResult(result);
            mResultAdapter.notifyDataSetChanged();

            String xyjval = (String) SharedPreferencesUtils.getParam(measure_xy_add.this, "xyjval", "");
            Log.i("xyjval1", xyjval);

            Log.i("size", mResultAdapter.getData().size()+"");
            if(mResultAdapter.getData().size()>0){
                for (int i=0; i<mResultAdapter.getData().size(); i++) {
                    ScanResult entity = mResultAdapter.getItem(i);
                    Log.i("xyjval22", entity.getDevice().getAddress());
                    Log.i("xyjval33", entity.getDevice().getAddress().equals(xyjval)+"");
                    if (entity.getDevice().getAddress().equals(xyjval)) {
                        entityDefault = entity;
                        break;
                    }
                }
            }
            for (ScanResult entity : mResultAdapter.getData()) {
                if (entity.getDevice().getAddress().equals(xyjval)) {
                    entityDefault = entity;
                    break;
                }
            }
//            此处为自动连接已经绑定并发现了的设备
//            if(null != entityDefault) {
////                progressDialog.dismiss();
//////                Intent intent = new Intent(measure_xy_add.this, CodeMeasureActivity.class);
//////                startActivity(intent);
//                Log.i("xyjval22333", entityDefault.getDevice().getAddress());
//                mBluetoothService.cancelScan();
//                bg = mBluetoothService.connectDevice(entityDefault);
//                mResultAdapter.clear();
//                mResultAdapter.notifyDataSetChanged();
//
//            }
        }

        @Override
        public void onScanComplete() {
            Log.i("onScanComplete","5");
            img_loading.clearAnimation();
            btn_start.setEnabled(true);
            btn_stop.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onConnecting() {
            Log.i("onConnecting","6");
            progressDialog.show();
        }

        @Override
        public void onConnectFail() {
            Log.i("onConnectFail","7");
            img_loading.clearAnimation();
            btn_start.setEnabled(true);
            btn_stop.setVisibility(View.INVISIBLE);
            progressDialog.dismiss();
        }

        @Override
        public void onDisConnected() {
            Log.i("onDisConnected","8");
            progressDialog.dismiss();
            mResultAdapter.clear();
            mResultAdapter.notifyDataSetChanged();
            img_loading.clearAnimation();
            btn_start.setEnabled(true);
            btn_stop.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onServicesDiscovered() {
            Log.i("onServicesDiscovered","9");
            progressDialog.dismiss();
//            Intent intent = new Intent(measure_xy_add.this, CodeDemoActivity.class);
            Intent intent = new Intent(measure_xy_add.this, CodeMeasureActivity.class);
            startActivityForResult(intent, 19);

        }
    };

    @Override
    public final void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 12:
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                            onPermissionGranted(permissions[i]);
                        }
                    }
                }
                break;
        }
    }

    /**
     * 检查权限
     */
    private void checkPermissions() {
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, 12);
        }
    }

    /**
     * 权限获取
     * @param permission
     */
    private void onPermissionGranted(String permission) {
        switch (permission) {
            case Manifest.permission.ACCESS_FINE_LOCATION:
                if (mBluetoothService == null) {
                    bindService();
                } else {
                    Log.i("scanDevice","222");
                    mBluetoothService.scanDevice();
                }
                break;
        }
    }
}
